import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';

import ReactEchartsCore from '../Core/EchartsReactCore';

import { titleTextStyle, pieSeriesConfig } from '../../itemDefaultConfig';
import Empty from '../Empty';

class PieChart extends PureComponent {
  getOption() {
    const {
      config: {
        title, legend, tooltip, showTitle, series, ...otherConfig
      },
      radius,
      center,
    } = this.props;

    return {
      title: {
        ...titleTextStyle,
        show: showTitle, // title.show优先级高于showTitle
        ...title,
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)',
        ...tooltip,
      },
      legend: {
        top: 'bottom',
        type: 'scroll',
        itemGap: 15,
        icon: 'pin',
        ...legend,
      },

      series: (series || []).map((item) => ({
        ...pieSeriesConfig,
        radius,
        center,
        ...item,
      })),
      ...otherConfig,
    };
  }

  getEchartsInstance() {
    if (!this.chartRef) return;

    return this.chartRef.getEchartsInstance();
  }

  saveRef = (node) => {
    this.chartRef = node;
  }

  render() {
    const {
      config: { series },
      empty: EmptyComponent,
      ...rest
    } = this.props;

    if (!series.length) {
      return EmptyComponent ? <EmptyComponent /> : <Empty />;
    }

    return <ReactEchartsCore notMerge ref={this.saveRef} config={this.getOption()} {...rest} />;
  }
}

PieChart.propTypes = {
  theme: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
  showTitle: PropTypes.bool,
  style: PropTypes.object,
  className: PropTypes.string,
  radius: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
  center: PropTypes.array,
  config: PropTypes.shape({
    series: PropTypes.array.isRequired,
  }).isRequired,
};

PieChart.defaultProps = {
  style: {},
  classname: '',
  theme: 'macarons',
  showTitle: false,
  radius: ['35%', '50%'],
  center: ['50%', '50%'],
  config: {
    title: { text: '' },
    series: [
      {
        data: [
          {
            name: '示意1',
            value: 200,
          },
          {
            name: '示意2',
            value: 600,
          },
        ],
      },
    ],
  },
};

export default PieChart;
